<?php


namespace App\Services;


use App\Models\AuthGroup;
use App\Models\AuthRule;

class AuthService
{
    /**
     * @var static 单例模式
     */
    protected static $instance;

    /**
     * 单例模式
     */
    public static function getInstance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }

    protected $admin;
    /**
     * 模块类型
     */
    const MODEL_ADMIN = 1;//管理后台
    const MODEL_MERCHANT = 2;//供应商后台
    const MODEL_SALE = 3;//分销商后台

    const MOUDEL = [
        '1'=>['name'=>'admin','remarks'=>'管理后台'],//管理后台
        '2'=>['name'=>'supplier','remarks'=>'供应商后台'],//供应商后台
    ];
    const ADMIN_RULE = '*';//超级管理员权限

    /**
     * 过滤验证
     * [控制器=》'方法,方法']
     * @var string[]
     */
    const FILTER_CONTROLLER_ACTION =  [
        'Admin\\Auth'=>'getAuthRule,editPwd',
        'Admin\\Modules'=>'getCategory',
        'Supplier\\Auth'=>'getAuthRule,editPwd',
    ];

    /**
     * @param $admin array|\App\Models\NewAdmin
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2024/12/13
     */
    public function setAdmin($admin)
    {
        $this->admin = $admin;
    }

    public function getAdmin()
    {
        return $this->admin;
    }

    public function getAdminId()
    {
        return $this->getAdmin() ? $this->admin['id'] : 0;
    }

    public function getAdminName()
    {
        return $this->getAdmin() ? $this->admin['username'] : '';
    }

    /**
     * 检测权限
     * @param $rules
     * @return bool
     */
    public static function checkClassAction($rules){
        $flag = true;
        $controllerBase = [];
        $actionBase = [];

        if($rules == self::ADMIN_RULE){
            return $flag;
        }
        $authRule = AuthRule::where(['is_delete'=>CommonService::IS_DELETE_NOT,'status'=>CommonService::USER_STATUS_YES])
            ->whereIn('id',explode(',',$rules))
            ->select('controller','action','type')
            ->get();
        $authRule = $authRule?$authRule->toArray():[];
        if(!$authRule){
            $flag = false;
            return $flag;
        }

        $requestControllerAction = explode('@',request()->route()->action['controller']);
        $requestController = str_replace(
            'App\\Http\\Controllers\\',
            '',
            $requestControllerAction[0]
        );
        $requestController = str_replace('Controller','',$requestController);
        foreach ($authRule as $v){
            if($v['controller'] && $v['action']){
                $actionBaseParam = explode(',',$v['action']);
                foreach ($actionBaseParam as $baseVaule){
                    $actionBase[] = strtoupper($baseVaule);
                }

                $controller = explode(',',$v['controller']);
                foreach ($controller as $controllerValue){
                    $requestControllerMoude = explode('\\',$controllerValue);
                    if(isset($requestControllerMoude[1])){
                        $moudeName = $requestControllerMoude[0];
                        $moudeController = $requestControllerMoude[1];
                    }else{
                        $moudeName = self::MOUDEL[$v['type']]['name'];
                        $moudeController = $controllerValue;
                    }
                    $controllerBase[] = strtoupper($moudeName.'\\'.$moudeController);
                }
            }
        }

        foreach (self::FILTER_CONTROLLER_ACTION as $filterController=>$filterAction){
            $controllerBase[] = strtoupper($filterController);
            $filterActionValue = explode(',',$filterAction);
            foreach ($filterActionValue as $vavle){
                $actionBase[] = strtoupper($vavle);
            }
        }


        if(!in_array(strtoupper($requestController),$controllerBase) || !in_array(strtoupper($requestControllerAction[1]),$actionBase)){
            //无权限
            $flag = false;
        }
        return $flag;
    }

    public static function checkRuleId($rule,$selfRule){
        foreach ($rule as $v){
            if(!in_array($v,$selfRule)){
                return false;
            }
        }
        return true;
    }

    public static function checkRuleIdInc($rule,$selfRule,$groupId){
        $ruleResult = array_unique(array_merge($rule,$selfRule));
        //找到删除的权限
        $ruleResult = array_diff($ruleResult,$rule);
        $authGroup = AuthGroup::where([['pid',$groupId]])->select('id','rules')->get();
        $authGroup = $authGroup?$authGroup->toArray():[];
        foreach ($authGroup as $item){
            $rules = explode(',',$item['rules']);
            foreach($rules as &$ruleId){
                //存在就删除
                if($ruleResult && in_array($ruleId,$ruleResult)){
                    unset($ruleId);
                }
            }
            AuthGroup::where([['id',$item['id']]])->update(['rules'=>implode(',',$rules)]);
        }
    }

    /**
     * 过滤不验证的方法
     * @param $controller
     * @param $filterAction
     * @return bool
     */
    public static function checkFilter($controller,$filterAction){
        $requestFilter = str_replace(
            'App\\Http\\Controllers\\',
            '',
            $controller
        );
        $flag = false;
        if(!in_array($requestFilter,$filterAction)){
            $flag = true;
        }
        return $flag;
    }
}
